package com.jevons.muffin.net.loader;

import androidx.lifecycle.MutableLiveData;

import com.jevons.muffin.event.BaseActionEvent;
import com.jevons.muffin.event.LoadingDialogEvent;
import com.jevons.muffin.net.inter.IResponse;

import io.reactivex.Observable;
import io.reactivex.ObservableTransformer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

/**
 * Copyright 2020 JxGIS
 *
 * @file NormalLoader
 * @auth linaisheng
 * Created on 2021/6/30.
 * Description：
 */
public class NormalLoader extends BaseLoader {

    private MutableLiveData<BaseActionEvent> actionLiveData;

    public NormalLoader(MutableLiveData<BaseActionEvent> actionLiveData) {
        this.actionLiveData = actionLiveData;
    }

    protected final <T> Observable<T> observeWithLoadingParse(Observable<? extends IResponse<T>> observable) {
        return observable
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .map(new Function<IResponse<T>, T>() {
                    @Override
                    public T apply(@NonNull IResponse<T> tiResponse) throws Exception {
                        return doParse(tiResponse);
                    }
                }).compose(loadingTransformer());
    }

    public final  <T> ObservableTransformer<T, T> loadingTransformer() {
        return observable -> observable
                .subscribeOn(AndroidSchedulers.mainThread())
                .unsubscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnSubscribe(disposable -> startLoading())
                .doFinally(this::dismissLoading);
    }

    private void startLoading() {
        if (actionLiveData != null) {
            actionLiveData.setValue(BaseActionEvent.create(new LoadingDialogEvent(true)));
        }
    }

    private void dismissLoading() {
        if (actionLiveData != null) {
            actionLiveData.setValue(BaseActionEvent.create(new LoadingDialogEvent(false)));
        }
    }

}
